package com.tanhua.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.CommentApi;
import com.tanhua.api.mongo.PublishApi;
import com.tanhua.api.mongo.VideoApi;
import com.tanhua.domain.FreeZing;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.PageBeanVo;
import com.tanhua.domain.vo.PublishVo;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.task.Task;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private VideoApi videoApi;

    @Reference
    private PublishApi publishApi;

    @Reference
    private CommentApi commentApi;
    @Autowired
    private Task task;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public ResponseEntity findUsers(Integer page, Integer pagesize) {

        //分页查询userInfo表(mybatisPlus分页)
        IPage<UserInfo> iPage = userInfoApi.findUsers(page, pagesize);

        //返回pageBeanVo(UserInfo数据)
        PageBeanVo pageBeanVo = new PageBeanVo(page, pagesize, iPage.getTotal(), iPage.getRecords());
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findByUid(Long userId) {

        UserInfo userInfo = userInfoApi.findUserInfo(userId);
        return ResponseEntity.ok(userInfo);
    }

    public ResponseEntity findByvideos(Integer page, Integer pagesize, Long uid) {

        //分页查询当前用户的所有video
        PageBeanVo pageBeanVo = videoApi.findByvideos(page, pagesize, uid);
        List<Video> items = (List<Video>) pageBeanVo.getItems();

        List<VideoVo> videoVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(items)) {

            for (Video video : items) {
                //根据video的用户id查询userInfo
                UserInfo userInfo = userInfoApi.findUserInfo(uid);
                //封装videoVo给pageBeanVo返回
                VideoVo videoVo = new VideoVo();
                BeanUtil.copyProperties(userInfo, videoVo);
                BeanUtil.copyProperties(video, videoVo);
                //手动封装id
                videoVo.setId(video.getId().toString());
                //手动封装封面
                videoVo.setCover(video.getPicUrl());
                //手动封装小视频说明
                videoVo.setSignature(video.getText());
                videoVo.setId(video.getId().toString());
                videoVoList.add(videoVo);
            }
        }

        pageBeanVo.setItems(videoVoList);

        return ResponseEntity.ok(pageBeanVo);

    }

    public ResponseEntity messages(Integer page, Integer pagesize, Long uid, Integer state) {

        // 分页查询动态
        PageBeanVo pageBeanVo = publishApi.messages(page, pagesize, uid, state);
        List<Publish> items = (List<Publish>) pageBeanVo.getItems();

        List<PublishVo> voList = new ArrayList();
        if (CollectionUtil.isNotEmpty(items)) {
            for (Publish publish : items) {
                // 查询userInfo
                UserInfo userInfo = userInfoApi.findUserInfo(publish.getUserId());
                //封装vo给pageBean
                PublishVo vo = new PublishVo();
                vo.setUserInfo(userInfo);
                vo.setPublish(publish);
                vo.setCreateDate(new DateTime(publish.getCreated()).toString("yyyy-MM-dd HH:mm"));
                vo.setId(publish.getId().toString());
                voList.add(vo);
            }
        }
        pageBeanVo.setItems(voList);

        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findByPublishId(String id) {

        Publish publish = publishApi.findById(id);
        UserInfo userInfo = userInfoApi.findUserInfo(publish.getUserId());
        PublishVo vo = new PublishVo();
        vo.setUserInfo(userInfo);
        vo.setPublish(publish);
        vo.setUserId(userInfo.getId());
        vo.setId(publish.getId().toString());
        vo.setCreateDate(new DateTime(publish.getCreated()).toString("yyyy-MM-dd HH:mm"));

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findByComments(Integer page, Integer pagesize, String messageID) {

        //根据publishId做comment的分页查询
        PageBeanVo pageBeanVo = commentApi.findComment(messageID, page, pagesize);
        List<Comment> items = (List<Comment>) pageBeanVo.getItems();

        List<CommentVo> voList = new ArrayList();
        if (CollectionUtil.isNotEmpty(items)) {
            for (Comment comment : items) {
                // 获取userInfo
                UserInfo userInfo = userInfoApi.findUserInfo(comment.getUserId());
                // 封装commentVo给pageBean返回
                CommentVo vo = new CommentVo();
                BeanUtil.copyProperties(userInfo, vo);
                BeanUtil.copyProperties(comment, vo);
                vo.setId(comment.getId().toString());
                voList.add(vo);

            }
        }

        pageBeanVo.setItems(voList);

        return ResponseEntity.ok(pageBeanVo);

    }

    //动态通过
    public ResponseEntity publishPass(List<String> list) {
        publishApi.pass(list);
        String message = "通过";
        return ResponseEntity.ok(message);
    }

    //冻结用户
    public ResponseEntity freezeUser(FreeZing freeZing) {
        Integer day = freeZing.getFreezingTime();
        if (day == 1) {
            //将前台传入的用户冻结信息存入redis中
            stringRedisTemplate.opsForValue().set("freeZing_" + freeZing.getUserId(), JSON.toJSONString(freeZing), 3, TimeUnit.DAYS);
            //传入3天的毫秒值，也就是自动解冻时间
            task.timer(freeZing.getUserId().longValue(), 3 * 24 * 60 * 60 * 1000l);
        } else if (day == 2) {
            //将前台传入的用户冻结信息存入redis中
            stringRedisTemplate.opsForValue().set("freeZing_" + freeZing.getUserId(), JSON.toJSONString(freeZing), 7, TimeUnit.DAYS);
            //传入7天的毫秒值，也就是自动解冻时间
            task.timer(freeZing.getUserId().longValue(), 7 * 24 * 60 * 60 * 1000l);
        } else {
            //永久冻结
            stringRedisTemplate.opsForValue().set("freeZing_" + freeZing.getUserId(), JSON.toJSONString(freeZing));
        }
        userInfoApi.freezeUser(freeZing.getUserId());
        return ResponseEntity.ok(null);
    }

    //解冻用户
    public ResponseEntity unfreezeUser(String userId) {
        //删除redis中的用户冻结信息
        stringRedisTemplate.delete("freeZing_" + userId);
        //修改数据库的用户权限状态
        userInfoApi.unfreezeUser(userId);
        return ResponseEntity.ok(null);
    }
}
